/**
 * app.js
 */
// var session_key='';
App({
 user:{
   session_key: '',
   session_id:'',
   user_id:null,
   isAuthor:0,
   header:'',
   aid :3, //AppId
   shareTitle: "最懂女人生活馆",
   shareDesc:"最懂女人生活馆",
 },
 path: {
    // api: 'http://apiwxxcx.youmeng.com?service=',// 接口 测试
    // url: 'http://demowxxcx.youmeng.com',//后台地址 测试

   api: 'https://apiwxxcx.youmeng.com/v1/?service=',// 接口 生产
   url: 'http://adminwxxcx.youmeng.com'//后台地址 生产
 },

  onLaunch: function () {
    var that = this;
    that.sessionId(that);
  },
  sessionId: function(that){
    that.user.session_key = wx.getStorageSync('session_key');
    that.user.session_id = wx.getStorageSync('session_id');
    that.user.user_id = wx.getStorageSync('session_id');
    if (that.user.session_id != "" && that.user.session_id != null) {
      that.user.header = { 'content-type': 'application/x-www-form-urlencoded', 'Cookie': 'PHPSESSID=' + that.user.session_id }
    } else {
      that.user.header = { 'content-type': 'application/x-www-form-urlencoded' }
      that.sessionKey(that);
    }  
    
  },
  sessionKey: function (that){
    // that.login();
    // return;
    wx.request({
      url: that.path.api + 'Member.Auth',
      data: { md5key: that.user.session_key },
      method: "POST",
      header: that.user.header,
      success: function (response) {
        var result = response.data;
        if (result.ret != 200) {
          that.login();
        }
      }
    })
  },
  getUserInfo: function (cb) {
    var that = this;
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //调用登录接口
      wx.login({
        success: function () {
          wx.getUserInfo({
            success: function (res) {
              that.globalData.userInfo = res.userInfo;
              typeof cb == "function" && cb(that.globalData.userInfo)
            }
          })
        }
      });
    }
  },
  globalData: {
    userInfo: null
  },

  login: function (redirect = '') {
    var that = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          //发起网络请求 登录
          wx.request({
            url: that.path.api + 'Member.Login',
            data: { wxcode: res.code,aid:that.user.aid },
            async: false,
            method: "POST",
            header: that.user.header,
            success: function (response) {
              var result = response.data;
              if (result.ret == 200) {
                that.user.session_key = result.data.md5key;
                that.user.session_id = result.data.sessid;
                wx.setStorageSync('session_key', result.data.md5key);
                wx.setStorageSync('session_id', result.data.sessid);
                that.sessionId(that);
                that.userInfo(that);
                wx.showToast({
                  title: '加载中',
                  icon: 'loading',
                  duration: 1000
                });
                if (redirect != '') {
                  wx.navigateBack({
                    url: redirect
                  })
                }
              } else {
                console.log(result.msg);
              }
            }
          });
          
          
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
    
  },


  // 传入用户信息
  userInfo:function(that){
    wx.getUserInfo({
      success: function (res) {
        //发起网络请求 登录
        that.user.isAuthor = 1;
        wx.request({
          url: that.path.api + 'Member.UserInfo',
          data: {
            md5key: that.user.session_key,
            aid: that.user.aid,
            nickname: res.userInfo.nickName,
            avatarurl: res.userInfo.avatarUrl,
            gender: res.userInfo.gender
          },
          async: false,
          method: "POST",
          header: that.user.header,
          success: function (response) {
            var result = response.data;
            if (result.ret == 200) {
              that.user.user_id = result.data;
              wx.setStorageSync('user_id', result.data);
            } else {
              console.log(result.msg);
            }
          }
        });
      },
    })
  },
  
  // 毫秒转换日期
  getMakeDate: function (str) {
    var oDate = new Date(str*1000),
      oYear = oDate.getFullYear(),
      oMonth = oDate.getMonth() + 1,
      oDay = oDate.getDate(),
      oTime = oYear+'年'+ oMonth + '月' + oDay + '日';//最后拼接时间  
    return oTime;
  },

  // 毫秒转换为与当前时间的关系
  getDateList:function(str,now){
    var oDate = str;
    var time=now-oDate;
    var timeStr="";
    if (time<60){
      timeStr=time+"秒前";
    }
    if (time >= 60&&time<3600) {
      timeStr = parseInt(time/60) + "分钟前";
    }
    if (time >= 3600 && time < 86400) {
      timeStr = parseInt(time / 3600) + "小时前";
    }
    if (time >= 86400 && time < 2592000) {
      timeStr = parseInt(time / 86400) + "天前";
    }
    if (time >= 2592000) {
      timeStr = parseInt(time / 2592000) + "月前";
    }
    return timeStr;
  },
  // 支付
  getPay: function (orderno, detail) {
    var that=this;
    wx.request({
      url: that.path.api + 'Order.WechatUnifiedOrder',
      data: {
        md5key: that.user.session_key,
        orderno: orderno,
        detail: detail,
        aid:that.user.aid,
      },
      async: false,
      method: "POST",
      header: that.user.header,
      success: function (response) {
        var result = response.data;
        if (result.ret == 200) {
          var timeStamp = result.data.timeStamp;
          var nonceStr = result.data.nonceStr;
          var packAge = result.data.package;
          var paySign = result.data.paySign;
          wx.requestPayment({
            "timeStamp": timeStamp,
            "nonceStr": nonceStr,
            "package": packAge,
            "signType": "MD5",
            "paySign": paySign,
            'success': function (res) {
              wx.showModal({
                showCancel: false,
                title: '',
                content: "支付成功！",
                success: function (res) {
                  wx.redirectTo({
                    url: '/pages/user/myorder/myorder?ostatus=' + 2,
                  })
                }
              });
            },
            'fail': function (res) {
              wx.showModal({
                showCancel: false,
                title: '',
                content: "支付失败！",
                success: function (res) {
                  wx.redirectTo({
                    url: '/pages/user/myorder/myorder?ostatus=' + 1,
                  })
                }
              });
            }
          })
        } else {
          wx.showModal({
            showCancel: false,
            title: '',
            content: "库存不足，请重新选择",
            success: function (res) {
              wx.redirectTo({
                url: '/pages/index/index',
              })
            }
          });
        }
      }
    });

  },

  // 价格补0
  returnFloat: function (value) {
    var value = Math.round(parseFloat(value) * 100) / 100;
    var xsd = value.toString().split(".");
    if(xsd.length == 1) {
      value = value.toString() + ".00";
      return value;
    }
    if (xsd.length > 1) {
      if (xsd[1].length < 2) {
        value = value.toString() + "0";
      }
      return value;
    }
    }
  
});


